﻿#region << 版 本 注 释 >>
/*
 * ========================================================================
 * Copyright(c) 北京天大天科科技发展有限公司, All Rights Reserved.
 * ========================================================================
 *  
 * 【当前类文件的功能】
 *  
 * CLR版本：4.0.30319.34014
 * 作者：杨朋飞  时间：2015/4/18 10:08:30
 * 文件名：ToolsHelper
 * 版本：V1.0.0
 * 
 * 修改者：           时间：               
 * 修改说明：
 * ========================================================================
*/
#endregion

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;

namespace YPF_CommonMethod
{
    public static class ToolsHelper
    {
        /// <summary>
        /// 获取GUID随机字符串,除去“—”显示的信息
        /// </summary>
        public static string GetGuidInfo()
        {
            return Guid.NewGuid().ToString("N");
        }

        #region----------------将传递过来的字符串按照需要的分隔符转换成int[]和string[]-------------------

        /// <summary>
        /// 以指定的char类型的符号作为分隔符将指定的字符串分割成int数组
        /// </summary>
        /// <param name="stringComma">需要分割的字符串</param>
        /// <param name="strSplit">char类型的分隔符</param>
        /// <returns></returns>
        public static int[] ConvertIntArrayInfo(string stringComma, char strSplit = ',')
        {
            string[] stringArray = stringComma.Split(new[] { strSplit });
            var intPurchaseOrderIdS = new int[stringArray.Count()];
            for (int i = 0; i < stringArray.Count(); i++)
            {
                intPurchaseOrderIdS[i] = Convert.ToInt32(stringArray[i]);
            }
            return intPurchaseOrderIdS;
        }

        /// <summary>
        /// 以指定字符串作为分割符将指定字符串分割成数组
        /// </summary>
        /// <param name="value">要分割的字符串</param>
        /// <param name="strSplit">字符串类型的分隔符</param>
        /// <param name="removeEmptyEntries">是否移除数据中元素为空字符串的项</param>
        /// <returns>返回分割后的字符串数组</returns>
        public static string[] ConvertStringInfo(this string value, string strSplit = ",",
            bool removeEmptyEntries = false)
        {
            return value.Split(new[] { strSplit },
                removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
        }

        #endregion

        #region 转全角的函数(SBC case)

        /// <summary>
        /// 转全角的函数(SBC case)
        /// </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>全角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>        
        public static string ToSbc(string input)
        {
            //半角转全角：
            char[] c = input.ToCharArray();

            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char) 12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char) (c[i] + 65248);
            }

            return new string(c);
        }

        #endregion

        #region 转半角的函数(DBC case)

        /// <summary>
        /// 转半角的函数(DBC case)
        /// </summary>
        /// <param name="input">任意字符串</param>
        /// <returns>半角字符串</returns>
        ///<remarks>
        ///全角空格为12288，半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是：均相差65248
        ///</remarks>
        public static string ToDbc(string input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char) 32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char) (c[i] - 65248);
            }
            string str = new string(c);
            //转化成大写
            return str.ToUpper();
        }

        #endregion

        #region 将十进制的byte数组转化为字符串

        /// <summary>
        /// 将十进制的byte数组转化为字符串
        /// </summary>
        /// <param name="bytSource">byte数组名称</param>
        /// <param name="iStart">起始位置，从0开始</param>
        /// <param name="iLength">截取位数</param>
        /// <returns></returns>
        public static string DecConverString(byte[] bytSource, int iStart, int iLength)
        {
            string strConvertResult = string.Empty;

            for (int i = iStart; i < iStart + iLength; i++)
            {
                int iValue = Convert.ToInt32(bytSource[i]) - 48;
                strConvertResult += iValue.ToString();
            }

            return strConvertResult;
        }

        #endregion

        #region 根据图片路径，将图片转化为byte[]格式

        /// <summary>
        /// 根据图片路径，将图片转化为byte[]格式
        /// </summary>
        /// <param name="strImagePath"></param>
        /// <returns></returns>
        public static byte[] ChangeImgToByte(string strImagePath)
        {
            Image image = Image.FromFile(strImagePath);
            MemoryStream ms = new MemoryStream();
            image.Save(ms, ImageFormat.Jpeg);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            byte[] buffer = new byte[ms.Length];
            ms.Read(buffer, 0, (int) ms.Length); //这里已经转成了字节   
            return buffer;
        }

        #endregion

        #region 将byte[]转化为Image格式

        /// <summary>
        /// 将byte[]转化为Image格式
        /// </summary>
        /// <param name="bytImage">byte[]数组</param>
        /// <returns></returns>
        public static Image ChangeByteToImg(byte[] bytImage)
        {
            if (bytImage != null)
            {
                MemoryStream ms = new MemoryStream(bytImage); //将字节数组存入到二进制流中 
                //ms.Position = 0;
                Image img = Image.FromStream(ms);
                //ms.Close();
                return img;
            }
            return null;
        }

        #endregion

        #region 从汉字转换到16进制

        /// <summary>
        /// 从汉字转换到16进制
        /// </summary>
        /// <param name="s"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <param name="fenge">是否每字符用逗号分隔</param>
        /// <returns></returns>
        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length%2) != 0)
            {
                s += " "; //空格
                //throw new ArgumentException("s is not valid chinese string!");
            }

            Encoding chs = Encoding.GetEncoding(charset);

            byte[] bytes = chs.GetBytes(s);

            string str = "";

            for (int i = 0; i < bytes.Length; i++)
            {
                str += string.Format("{0:X}", bytes[i]);
                if (fenge && (i != bytes.Length - 1))
                {
                    str += string.Format("{0}", ",");
                }
            }

            return str.ToLower();
        }

        #endregion


        #region 从16进制转换成汉字

        /// <summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length%2 != 0)
            {
                hex += "20"; //空格
                //throw new ArgumentException("hex is not a valid number!", "hex");
            }
            // 需要将 hex 转换成 byte 数组。
            byte[] bytes = new byte[hex.Length/2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。
                    bytes[i] = byte.Parse(hex.Substring(i*2, 2),
                        NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message.
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }

            Encoding chs = Encoding.GetEncoding(charset);

            return chs.GetString(bytes);
        }

        #endregion


        #region 十六进制转换字节数组

        /// <summary>
        /// 十六进制转换字节数组
        /// </summary>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static byte[] HexStringToByteArray(string charset)
        {
            charset = charset.Replace(" ", "");

            byte[] buffer = new byte[charset.Length/2];

            for (int i = 0; i < charset.Length; i += 2)
            {
                buffer[i/2] = (byte) Convert.ToByte(charset.Substring(i, 2), 16);
            }

            return buffer;
        }

        #endregion


        #region 字节数组转换十六进制

        /// <summary>
        /// 字节数组转换十六进制
        /// </summary>
        /// <param name="btData">字节数组</param>
        /// <returns></returns>
        public static string ByteArrayToHexString(byte[] btData)
        {
            StringBuilder sbData = new StringBuilder(btData.Length*3);

            foreach (byte b in btData)
            {
                sbData.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
            }

            return sbData.ToString().ToUpper();
        }

        #endregion

    }
}
